/*
 
   isemptycell.c -- return a boolean array with "isempty" over a cell array

FORMAT:       iec = isemptycell(c)

Input fields:

      c           N-d cell array

Output fields:

      iec         boolean array with isempty(c{i, j, ...})

% Version:  v0.7g
% Build:    9100818
% Date:     Oct-08 2009, 6:37 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

*/

#include "mex.h"
#include "matrix.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

    const int *dim;
    int ndim = 2, nelem = 0;
    char *out;
    const mxArray *cell;
    
    /* argument check */
    if (nrhs != 1 || nlhs > 1)
		mexErrMsgTxt("Bad number of input/output arguments.");
    if (!mxIsCell(*prhs))
		mexErrMsgTxt("Input argument must be of type cell.");
    
    /* get dimensions */
    ndim = mxGetNumberOfDimensions(*prhs);
    dim = mxGetDimensions(*prhs);
    nelem = mxGetNumberOfElements(*prhs);
    
    /* create output */
    *plhs = mxCreateNumericArray(ndim, dim, mxLOGICAL_CLASS, mxREAL);
    if (*plhs == NULL)
        mexErrMsgTxt("Couldn't allocate memory for output.");
    if (nelem == 0)
        return;
    out = (char *) mxGetData(*plhs);
    if (out == NULL)
        mexErrMsgTxt("Invalid pointer of output data.");
    
    /* iterate over elements */
    for(out = &out[--nelem]; nelem >= 0; --nelem) {
        cell = (const mxArray *) mxGetCell(*prhs, nelem);
        if (cell == NULL)
            *out-- = 1;
        else
            *out-- = (mxGetNumberOfElements(cell) == 0) ? 1 : 0;
    }
}
